package com.dvd.controller;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.LinkedList;
import com.dvd.model.DVDItem;
import java.util.List;

public class AddDVDServlet extends HttpServlet {
   public void doPost(HttpServletRequest request, HttpServletResponse response)
                            throws IOException, ServletException {
        List errorMsgs = new LinkedList();
        try {
            request.setCharacterEncoding("Big5");
            // Retrieve form parameters
            String title = request.getParameter("title");
            String year = request.getParameter("year");
            // Did the user type in a genre?
            String genre = request.getParameter("newGenre");
            // If not, use the drop-down list value
            if ((genre == null) || (genre.trim().length() == 0)) {
                genre = request.getParameter("genre");
            }
            //     Form verification
            if ( title.length() == 0 ) {
              errorMsgs.add("Please enter the DVD title.");
            }
            if ( year.length() == 0 ) {
                errorMsgs.add("Please enter the year of release for the DVD.");
              }
              if ( ! errorMsgs.isEmpty() ) {
                request.setAttribute("errorMsgs", errorMsgs);
                RequestDispatcher view =
                       request.getRequestDispatcher("/add_dvd.view");
                view.forward(request, response);
                return;
              }
              // Business logic
              DVDItem item = new DVDItem(title, year, genre);

              // Store the item on the request-scope
              request.setAttribute("dvdItem", item);

              // Dispatch to Success view
              RequestDispatcher view =
                       request.getRequestDispatcher("/success.view");
              view.forward(request, response);
              // Handle any unexpected expections
          } catch (RuntimeException e) {
              errorMsgs.add("An unexpected error: " + e.getMessage());
              request.setAttribute("errorMsgs", errorMsgs);
              RequestDispatcher view = 
                       request.getRequestDispatcher("/add_dvd.view");
              view.forward(request, response);        
          }
      }
  }
